<template>
  <view class="ava-datail">
    <tn-popup v-model="show" radius="20rpx" open-direction="bottom" style="z-index: 100;">
      <scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
        @scrolltolower="lower" @scroll="scroll">
        <view class="popStyle">
          <view class="aiStyle" v-for="(item,index) in hairData" :key="index">
            <!-- #ifdef H5 -->
            <image style="width: 170rpx;" :src="getImg(item.sattDir)" mode="widthFix"
              :class="{'checked':checked===index}" @click="swichImg(item,index)"></image>
            <!-- #endif -->
            <!-- #ifdef MP -->
            <image :src="getImg(item.sattDir)" mode="widthFix" :class="{'checked':checked===index}"
              @click="swichImg(item,index)"></image>
            <!-- #endif -->
          </view>
        </view>
      </scroll-view>
      <button style="background-color: rgba(27, 224, 89); width: 450rpx; margin-bottom: 40rpx;" @click="chooseHair">确定生成
        <text style="color: red;">(消耗1积分)</text>
      </button>
    </tn-popup>
    <view class="title-avatar">
      <image v-if="flag == 0" class="img" :src="pic" mode="aspectFill"></image>
      <image v-else class="img" :src="getImg(pic)" mode="aspectFill"></image>
    </view>
    <view class="two-btn">
      <button class="hairSty" @click="showPopup">我型我发GO</button>
      <button v-if="picUrl != ''" class="savePic" @click="savaPic(picUrl)">保存到手机相册</button>
    </view>
  </view>
  <tn-overlay v-model:show="showOverlay" :duration="250" :opacity="0.4" />
  <!-- <view class="mask" v-show="isShow">
    <div class="loader"></div>
    <p style="margin-top: 80%;  font-family: Arial, sans-serif;color: #3498db;font-size: 28rpx; font-weight: 700;">
      加载中...</p>
  </view> -->
  <!-- #ifdef H5 -->
  <view class="mask" v-show="isShow">
    <div class="loader"></div>
    <p style="margin-top: 100%;  font-family: Arial, sans-serif;color: #3cb4ff;font-size: 28rpx; font-weight: 700;">
      加载中...</p>
  </view>
  <!-- #endif -->

  <!-- #ifdef MP -->
  <view class="mask" v-show="isShow">
    <div class="loader"></div>
    <p style="margin-top: 90%;  font-family: Arial, sans-serif;color: #3cb4ff;font-size: 28rpx; font-weight: 700;">
      加载中...</p>
  </view>
  <!-- #endif -->
</template>

<script setup>
  import {
    getHairStyleApi,
    getAiChangeFile,
    getHairTime
  } from '@/api/hirstyStyle.js'
  import getImgUrl from '@/config/img.js'
  import {
    reactive,
    ref,
    onMounted
  } from 'vue'
  import {
    onLoad,
  } from "@dcloudio/uni-app"
  const show = ref(false) //是否弹窗
  const hairData = ref([]) //接收头发类型
  const pic = ref("") //无拼接照片地址
  const url = ref("") //有拼接
  const checked = ref(null) //是否选中边框
  // const getId = ref("")
  const featureId = ref("")
  const flag = ref(0)
  const picUrl = ref("")
  const attIdHM = ref("") //素材发型id
  const attidPH = ref("") //人脸素材id
  const setTime = ref("") //设置时间
  const isShow = ref(false) //遮罩层 
  onLoad((option) => {
    pic.value = option.pic //拍照或上传的图片
    attidPH.value = option.featureId //人脸素材id
  })
  //弹出hair style
  const showPopup = () => {
    show.value = true;
    //调用发型接口
    let params = {
      limit: 20,
      page: 1
    }
    uni.showLoading({
      title: '加载中'
    })
    getHairStyleApi(params).then(res => {
      console.log(res, '发型数据')
      hairData.value = res.data.list
      uni.hideLoading()
    })
  }
  // 获取图片地址
  const getImg = (url) => {
    return getImgUrl(url)
  }
  //关闭弹窗
  const closePop = () => {
    show.value = false
  }
  //选中发型
  let filePath = ref('')

  function swichImg(item, index) {
    checked.value = index
    filePath.value = getImg(item.sattDir)
    attIdHM.value = item.attId //发型素材的id

  }

  function chooseHair() {
    isShow.value = true
    //设置加载时间
    const setEnd = setInterval(() => {
      let params = {
        attidPH: attidPH.value
      }
      getHairTime(params).then(res => {
        setTime.value = res.data
        if (res.data == true) {
          getTimeAi()
          clearInterval(setEnd)
        } else if (res.code !== 200) {
          isShow.value = false
        }
      })
    }, 1000)
    const getTimeAi = () => {
      let params = {
        attidHM: attIdHM.value, // 发型id
        attidPH: attidPH.value //人脸
      }
      getAiChangeFile(params).then(res => {
        show.value = false
        pic.value = res.data.sattDir
        flag.value = 1
        picUrl.value = getImg(pic.value)
      })
      isShow.value = false
    }
  }

  //保存网络图片到本地
  function savaPic(picUrl) {
    console.log('地址', picUrl)
    uni.showLoading({
      title: "保存中...",
    })
    // #ifdef MP
    uni.downloadFile({
      url: picUrl,
      success: (res) => {
        console.log('成功', res)
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (res) => {
              setTimeout(function() {
                uni.hideLoading();
              }, 5000);
              return uni.showToast({
                title: "保存成功！",
              });
            },
            fail: (res) => {
              console.log(res.errMsg);
              return uni.showToast({
                title: res.errMsg,
              });
            },
            //无论成功失败都走的回调
            complete: (res) => {
              uni.hideLoading();
            },
          });
        } else {
          uni.showToast({
            title: '网络错误',
          })
        }
      }
    })
    // #endif

    // #ifdef H5
    var oA = document.createElement("a");
    oA.download = '保存'; // 设置下载的文件名，默认是'下载'
    oA.href = picUrl;
    document.body.appendChild(oA);
    oA.click();
    oA.remove(); // 下载之后把创建的元素删除
    // #endif
  }
</script>

<style scoped lang="scss">
  .mask {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9999;
    width: 100%;
    height: 100vh;
    text-align: center;
    background: rgba(0, 0, 0, 0.4);

    .loader {
      position: absolute;
      border: 8px solid #f3f3f3;
      border-top: 8px solid #3498db;
      border-radius: 50%;
      left: 40%;
      top: 30%;
      transform: translate(-50%, -50%);
      width: 70px;
      height: 70px;
      animation: spin 1s linear infinite;
      margin: 20px auto;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  }

  .popStyle {
    background-color: #fff;
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;
    padding-left: 26rpx;

    .aiStyle {
      width: 170rpx;
      height: 170rpx;
      margin-top: 10rpx;
      margin-left: 6rpx;

      .checked {
        border: 5rpx solid red;
      }
    }
  }


  .ava-datail {
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;

    .title-avatar {
      width: 600rpx;
      height: 800rpx;
      border-radius: 20rpx;
      overflow: hidden;

      .img {
        width: 100%;
        height: 100%;
        display: block;
      }
    }

    .xz-avat {
      width: 640rpx;
      height: 235rpx;
      padding: 20rpx;
      margin-top: 30rpx;
      border: 2rpx #f5f5f5 solid;
      border-radius: 20rpx;
      overflow: hidden;
    }

    .two-btn {
      height: 250rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-top: 100rpx;

      .savePic {
        width: 250rpx;
        height: 70rpx;
        margin-top: 100rpx;
        border-radius: 35rpx;
        text-align: center;
        line-height: 70rpx;
        font-size: 24rpx;
        background: linear-gradient(to right, #fa0fcd, 50%, #f91932);
      }

      .hairSty {
        width: 250rpx;
        height: 70rpx;
        border-radius: 35rpx;
        text-align: center;
        font-size: 24rpx;
        line-height: 70rpx;
        background: linear-gradient(to right, #f1dc0d, 50%, #72f119);
      }
    }
  }
</style>